package com.bw.skill;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.bw.skill.mvvm.viewmodel.SeckillValuesViewModel;
import com.bw.skill.mvvm.viewmodel.SkillViewModel;

import java.lang.ref.WeakReference;
import java.util.Date;

public
/**
 * @author Lishaohe
 * @description:
 * @date :2021/10/28 0028 上午 8:26
 *
 */
class TimeServer extends Service {
    private long time;
    private TimeHandler timeHandler;
    private TimeThread timeThread;
    public long getTime() {
        return time;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {


        time = intent.getLongExtra("time",0);
        timeHandler = new TimeHandler(this);
        timeThread = new TimeThread(timeHandler);
        timeThread.start();


        return START_NOT_STICKY;


    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new TimeBind();
    }

    public class TimeBind extends Binder{

        public TimeServer getTimeService(){
            return TimeServer.this;

        }
    }

    @Override
    public void onDestroy() {
        timeThread.isInterrupted();
        super.onDestroy();

    }

    public static class TimeHandler extends Handler{
        public WeakReference<TimeServer> weakReference;
        public TimeHandler(TimeServer server){
            weakReference = new WeakReference<>(server);
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0){
                if (weakReference ==null){
                    return;
                }
                if (weakReference.get() ==null){
                    return;
                }
                weakReference.get().time+=1;
//                LogUtils.e("weakReference.get().time"+weakReference.get().time);
//                SkillViewModel.bundle.putLong("time",weakReference.get().time);
                SeckillValuesViewModel.time1 = weakReference.get().time;
                Date date = TimeUtils.millis2Date(weakReference.get().time*1000);
                String s1 = TimeUtils.date2String(date);
                SkillViewModel.nowtime.set("当前时间："+s1);
            }
        }
    }
}
